import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Button,
  Table,
  Divider,
  Input,
  Modal,
  Popconfirm,
  message,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const { pathname } = window.location;

const modelNumberObj = {
  1: 'I7',
  2: 'YGF F7',
};

interface ImeiManagementProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  screen: string;
  hasPath: string;
}

interface ImeiManagementState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId: number;
  visable: boolean;
  imeiDetail: {
    id: number,
    imei: string,
    modelNumber: number,
  };
}

@connect(
  ({
    imeiManagement: { dataInfo },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    screen,
    hasPath,
    loading: loading.effects['imeiManagement/fetch'],
  }),
)
class ImeiManagement extends React.Component<ImeiManagementProps, ImeiManagementState> {
  columns = [
    {
      title: 'IMEI',
      dataIndex: 'imei',
    },
    {
      title: '码枪型号',
      dataIndex: 'modelNumber',
      render: (id: number) => <span>{modelNumberObj[id]}</span>,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
    },
    {
      title: '添加人',
      dataIndex: 'createUserName',
    },
    {
      title: '最新修改人',
      dataIndex: 'updateUserName',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id: number, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEditImei(record)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除当前IMEI吗？"
            okText="确定"
            cancelText="取消"
            className="operLink"
            onConfirm={() => this.delImei(id)}
          >
            删除
          </Popconfirm>
        </>
      ),
    },
  ];

  state: ImeiManagementState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
    visable: false,
    imeiDetail: {
      id: 0,
      imei: '',
      modelNumber: 0,
    },
  };

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  showModal = () => {
    this.setState({ visable: true });
  }

  hideModal = () => {
    this.setState({ imeiDetail: { id: 0, imei: '', modelNumber: 0 } });
    this.setState({ visable: false });
  }

  changeImei = (e: any) => {
    const { imeiDetail } = this.state;
    const { value } = e.target;
    if (/^[a-zA-Z0-9]*$/g.test(value)) {
      imeiDetail.imei = value;
      this.setState({ imeiDetail });
    }
  }

  changeModelNumber = (id: number) => {
    const { imeiDetail } = this.state;
    imeiDetail.modelNumber = id;
    this.setState({ imeiDetail });
  }

  /**
   * 新建IMEI
   */
  handleAddImei = () => {
    this.showModal();
  };

  /**
   * 编辑IMEI
   */
  handleEditImei = (record: any) => {
    const imeiDetail = {
      id: record.id,
      imei: record.imei,
      modelNumber: record.modelNumber,
    };
    this.setState({ imeiDetail });
    this.showModal();
  };

  // 查询
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: 'IMEI管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  // 重置
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: 'IMEI管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: 'IMEI管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  addOrEditImei = () => {
    const { imeiDetail } = this.state;

    if (!imeiDetail.modelNumber) {
      message.error('码枪型号不能为空！');
      return;
    }

    if (!imeiDetail.imei) {
      message.error('IMEI不能为空！');
      return;
    }

    this.hideModal();

    const { dispatch } = this.props;
    dispatch({
      type: 'imeiManagement/addOrEdit',
      payload: {
        params: imeiDetail,
        search: this.getQueryParams(),
      },
    });
  }

  /**
   * 删除IMEI
   */
  delImei = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'imeiManagement/delete',
      payload: {
        params: { id },
        search: this.getQueryParams(),
      },
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `imeiManagement/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      visable,
      imeiDetail,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      loading,
    } = this.props;

    const dataSource = dataInfo && dataInfo.list
      ? dataInfo.list.map((item: any) => {
        if (item.type !== 1) {
          item.logisName = item.gardenName;
        }
        return item;
      })
      : [];

    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="IMEI" colon={false}>
                  {getFieldDecorator('imei')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="码枪型号" colon={false}>
                  {getFieldDecorator('modelNumber')(
                    <Select
                      allowClear
                      placeholder="请选择"
                    >
                      {Object.keys(modelNumberObj).map((id: any) => (
                        <Option key={id} value={id}>
                          {modelNumberObj[id]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleAddImei}
            >
              新建IMEI
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />

          <Modal
            title={imeiDetail.id === 0 ? '添加IMEI' : '编辑IMEI'}
            visible={visable}
            onOk={this.addOrEditImei}
            onCancel={this.hideModal}
          >
            <Row gutter={24}>
              <Col md={16} sm={16}>
                <Form.Item label="码枪型号">
                  <Select
                    allowClear
                    placeholder="请选择"
                    style={{ width: '100%' }}
                    value={imeiDetail.modelNumber === 0 ? undefined : imeiDetail.modelNumber}
                    onChange={this.changeModelNumber}
                  >
                    {Object.keys(modelNumberObj).map((id: any) => (
                      <Option key={id} value={Number(id)}>
                        {modelNumberObj[id]}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col md={16} sm={16}>
                <Form.Item label="IMEI　　">
                  <Input
                    allowClear
                    placeholder="请输入IMEI"
                    value={imeiDetail.imei}
                    onChange={this.changeImei}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Modal>
        </Card>
      </>
    );
  }
}

export default Form.create<ImeiManagementProps>()(ImeiManagement);
